from flask import Blueprint, request, jsonify
from database import PresetDAO
from datetime import datetime
from utils.logger import get_logger

logger = get_logger(__name__)


def create_preset_routes(preset_dao: PresetDAO):
    """创建预设相关路由"""

    preset_bp = Blueprint('preset', __name__)

    @preset_bp.route('/presets', methods=['GET'])
    def get_presets():
        """获取预设列表"""
        try:
            presets = preset_dao.get_presets()

            items = []
            for preset in presets:
                items.append({
                    'id': preset['id'],
                    'name': preset['name'],
                    'description': preset['description'],
                    'canvas_width': preset['canvas_width'],
                    'canvas_height': preset['canvas_height'],
                    'output_format': preset['output_format'],
                    'video_scale': preset['video_scale'],
                    'video_x': preset['video_x'],
                    'video_y': preset['video_y'],
                    'bg_scale': preset['bg_scale'],
                    'bg_x': preset['bg_x'],
                    'bg_y': preset['bg_y'],
                    'keep_human_ratio': bool(preset['keep_human_ratio']),
                    'keep_bg_ratio': bool(preset['keep_bg_ratio']),
                    'created_time': preset['created_time'],
                    'updated_time': preset['updated_time']
                })

            return jsonify({'success': True, 'presets': items})

        except Exception as e:
            logger.error(f"获取预设失败: {e}")
            return jsonify({'success': False, 'message': '获取预设失败'}), 500

    @preset_bp.route('/presets', methods=['POST'])
    def save_preset():
        """保存预设"""
        try:
            data = request.get_json()

            # 验证必需字段
            required_fields = ['name', 'canvas_width', 'canvas_height', 'output_format']
            for field in required_fields:
                if field not in data:
                    return jsonify({
                        'success': False,
                        'message': f'缺少必需字段: {field}'
                    }), 400

            # 设置默认值
            defaults = {
                'description': '',
                'video_scale': 1.0,
                'video_x': 0,
                'video_y': 0,
                'bg_scale': 1.0,
                'bg_x': 0,
                'bg_y': 0,
                'keep_human_ratio': True,
                'keep_bg_ratio': True
            }

            for key, default_value in defaults.items():
                if key not in data:
                    data[key] = default_value

            success = preset_dao.save_preset(data)

            if success:
                return jsonify({'success': True, 'message': '预设保存成功'})
            else:
                return jsonify({'success': False, 'message': '保存预设失败'}), 500

        except Exception as e:
            logger.error(f"保存预设失败: {e}")
            return jsonify({'success': False, 'message': '保存预设失败'}), 500

    @preset_bp.route('/presets/<int:preset_id>', methods=['GET'])
    def get_preset(preset_id):
        """获取单个预设"""
        try:
            with preset_dao.db.get_connection() as conn:
                preset = conn.execute(
                    'SELECT * FROM presets WHERE id = ?', (preset_id,)
                ).fetchone()

            if not preset:
                return jsonify({'success': False, 'message': '预设不存在'}), 404

            preset_data = {
                'id': preset['id'],
                'name': preset['name'],
                'description': preset['description'],
                'canvas_width': preset['canvas_width'],
                'canvas_height': preset['canvas_height'],
                'output_format': preset['output_format'],
                'video_scale': preset['video_scale'],
                'video_x': preset['video_x'],
                'video_y': preset['video_y'],
                'bg_scale': preset['bg_scale'],
                'bg_x': preset['bg_x'],
                'bg_y': preset['bg_y'],
                'keep_human_ratio': bool(preset['keep_human_ratio']),
                'keep_bg_ratio': bool(preset['keep_bg_ratio']),
                'created_time': preset['created_time'],
                'updated_time': preset['updated_time']
            }

            return jsonify({'success': True, 'preset': preset_data})

        except Exception as e:
            logger.error(f"获取预设失败: {e}")
            return jsonify({'success': False, 'message': '获取预设失败'}), 500

    @preset_bp.route('/presets/<int:preset_id>', methods=['PUT'])
    def update_preset(preset_id):
        """更新预设"""
        try:
            data = request.get_json()
            data['id'] = preset_id  # 确保ID正确

            success = preset_dao.save_preset(data)

            if success:
                return jsonify({'success': True, 'message': '预设更新成功'})
            else:
                return jsonify({'success': False, 'message': '更新预设失败'}), 500

        except Exception as e:
            logger.error(f"更新预设失败: {e}")
            return jsonify({'success': False, 'message': '更新预设失败'}), 500

    @preset_bp.route('/presets/<int:preset_id>', methods=['DELETE'])
    def delete_preset(preset_id):
        """删除预设"""
        try:
            success = preset_dao.delete_preset(preset_id)

            if success:
                return jsonify({'success': True, 'message': '删除成功'})
            else:
                return jsonify({'success': False, 'message': '删除失败'}), 500

        except Exception as e:
            logger.error(f"删除预设失败: {e}")
            return jsonify({'success': False, 'message': '删除失败'}), 500

    @preset_bp.route('/presets/duplicate/<int:preset_id>', methods=['POST'])
    def duplicate_preset(preset_id):
        """复制预设"""
        try:
            with preset_dao.db.get_connection() as conn:
                original_preset = conn.execute(
                    'SELECT * FROM presets WHERE id = ?', (preset_id,)
                ).fetchone()

            if not original_preset:
                return jsonify({'success': False, 'message': '原预设不存在'}), 404

            # 创建新预设数据
            new_preset_data = {
                'name': f"{original_preset['name']} (副本)",
                'description': original_preset['description'],
                'canvas_width': original_preset['canvas_width'],
                'canvas_height': original_preset['canvas_height'],
                'output_format': original_preset['output_format'],
                'video_scale': original_preset['video_scale'],
                'video_x': original_preset['video_x'],
                'video_y': original_preset['video_y'],
                'bg_scale': original_preset['bg_scale'],
                'bg_x': original_preset['bg_x'],
                'bg_y': original_preset['bg_y'],
                'keep_human_ratio': original_preset['keep_human_ratio'],
                'keep_bg_ratio': original_preset['keep_bg_ratio']
            }

            success = preset_dao.save_preset(new_preset_data)

            if success:
                return jsonify({'success': True, 'message': '预设复制成功'})
            else:
                return jsonify({'success': False, 'message': '复制预设失败'}), 500

        except Exception as e:
            logger.error(f"复制预设失败: {e}")
            return jsonify({'success': False, 'message': '复制预设失败'}), 500

    @preset_bp.route('/presets/export', methods=['GET'])
    def export_presets():
        """导出所有预设"""
        try:
            presets = preset_dao.get_presets()

            export_data = []
            for preset in presets:
                export_data.append({
                    'name': preset['name'],
                    'description': preset['description'],
                    'canvas_width': preset['canvas_width'],
                    'canvas_height': preset['canvas_height'],
                    'output_format': preset['output_format'],
                    'video_scale': preset['video_scale'],
                    'video_x': preset['video_x'],
                    'video_y': preset['video_y'],
                    'bg_scale': preset['bg_scale'],
                    'bg_x': preset['bg_x'],
                    'bg_y': preset['bg_y'],
                    'keep_human_ratio': bool(preset['keep_human_ratio']),
                    'keep_bg_ratio': bool(preset['keep_bg_ratio'])
                })

            return jsonify({
                'success': True,
                'presets': export_data,
                'count': len(export_data),
                'exported_at': datetime.now().isoformat()
            })

        except Exception as e:
            logger.error(f"导出预设失败: {e}")
            return jsonify({'success': False, 'message': '导出预设失败'}), 500

    @preset_bp.route('/presets/import', methods=['POST'])
    def import_presets():
        """导入预设"""
        try:
            data = request.get_json()
            presets = data.get('presets', [])

            if not presets:
                return jsonify({'success': False, 'message': '没有要导入的预设'}), 400

            success_count = 0
            error_count = 0
            errors = []

            for preset_data in presets:
                try:
                    # 验证必需字段
                    required_fields = ['name', 'canvas_width', 'canvas_height', 'output_format']
                    missing_fields = [field for field in required_fields if field not in preset_data]

                    if missing_fields:
                        errors.append(f"预设 '{preset_data.get('name', '未知')}' 缺少字段: {', '.join(missing_fields)}")
                        error_count += 1
                        continue

                    # 设置默认值
                    defaults = {
                        'description': '',
                        'video_scale': 1.0,
                        'video_x': 0,
                        'video_y': 0,
                        'bg_scale': 1.0,
                        'bg_x': 0,
                        'bg_y': 0,
                        'keep_human_ratio': True,
                        'keep_bg_ratio': True
                    }

                    for key, default_value in defaults.items():
                        if key not in preset_data:
                            preset_data[key] = default_value

                    # 检查名称是否已存在，如果存在则添加后缀
                    original_name = preset_data['name']
                    name_suffix = 1

                    with preset_dao.db.get_connection() as conn:
                        while True:
                            existing = conn.execute(
                                'SELECT id FROM presets WHERE name = ?',
                                (preset_data['name'],)
                            ).fetchone()

                            if not existing:
                                break

                            preset_data['name'] = f"{original_name} ({name_suffix})"
                            name_suffix += 1

                    if preset_dao.save_preset(preset_data):
                        success_count += 1
                    else:
                        errors.append(f"保存预设 '{preset_data['name']}' 失败")
                        error_count += 1

                except Exception as e:
                    errors.append(f"处理预设时出错: {str(e)}")
                    error_count += 1

            # 构建响应消息
            if success_count > 0 and error_count == 0:
                message = f'成功导入 {success_count} 个预设'
            elif success_count > 0 and error_count > 0:
                message = f'成功导入 {success_count} 个预设，{error_count} 个失败'
            else:
                message = f'导入失败，{error_count} 个预设处理失败'

            return jsonify({
                'success': success_count > 0,
                'message': message,
                'success_count': success_count,
                'error_count': error_count,
                'errors': errors[:5]  # 只返回前5个错误
            })

        except Exception as e:
            logger.error(f"导入预设失败: {e}")
            return jsonify({'success': False, 'message': '导入预设失败'}), 500

    @preset_bp.route('/presets/batch-delete', methods=['POST'])
    def batch_delete_presets():
        """批量删除预设"""
        try:
            data = request.get_json()
            preset_ids = data.get('preset_ids', [])

            if not preset_ids:
                return jsonify({'success': False, 'message': '没有选择要删除的预设'}), 400

            success_count = 0
            error_count = 0

            for preset_id in preset_ids:
                try:
                    if preset_dao.delete_preset(preset_id):
                        success_count += 1
                    else:
                        error_count += 1
                except Exception as e:
                    logger.error(f"删除预设 {preset_id} 失败: {e}")
                    error_count += 1

            if success_count > 0:
                message = f'成功删除 {success_count} 个预设'
                if error_count > 0:
                    message += f'，{error_count} 个失败'

                return jsonify({
                    'success': True,
                    'message': message,
                    'success_count': success_count,
                    'error_count': error_count
                })
            else:
                return jsonify({
                    'success': False,
                    'message': f'删除失败，{error_count} 个预设删除失败'
                }), 500

        except Exception as e:
            logger.error(f"批量删除预设失败: {e}")
            return jsonify({'success': False, 'message': '批量删除失败'}), 500

    return preset_bp